const fse = require('fs-extra');
const path = require('path');
const modelTpl = require('./templates/model.tpl');

module.exports = {
    // 保存模型
    '/saveModelData': {
        method: 'post',
        data: async function(param, store, ctx) {
            let modelName = param.modelInfo.keyName;

            store.modelData.set({
                [modelName]: param.modelData
            });
            store.modelList.set({
                [modelName]: param.modelInfo
            });

            return {
                success: true
            }
        }
    },
    // 获取模型列表
    '/getModelList': {
        method: 'get',
        data: async function(param, store, ctx) {
            const modelList = await store.modelList.get();

            return {
                success: true,
                data: modelList
            }
        }
    },
    // 获取模型数据
    '/getModelData': {
        method: 'get',
        data: async function(param, store, ctx) {
            const modelData = await store.modelData.get(param.modelName);

            return {
                success: true,
                data: modelData
            }
        }
    },
    // 删除模型
    '/deleteModel': {
        method: 'post',
        data: async function(param, store, ctx) {
            let modelName = param.modelName;
            const res1 = await store.modelList.delete(modelName);
            const res2 = await store.modelData.delete(modelName);

            return {
                success: true
            }
        }
    },
    // 生成模型代码
    '/makeModelCode': {
        method: 'post',
        data: async function(param, store, ctx) {
            const modelName = param.modelName;
            const modelData = await store.modelData.get(modelName);
            let tplStr = modelTpl(modelData);
            let filePath = `${path.join(__dirname, './models')}/${modelName}.js`;

            fse.outputFileSync(filePath, tplStr);

            return {
                success: true
            }
        }
    }
}